/**
 * Created by Nicolas at 2015-08-24
 */
/*$(document).ready(function(){
    $("input[name=specBtn]:eq(0)").parent().addClass("am-active");
});*/
grApp.filter('filterInventory',function(){
    var result='';
    return function(item){
        if(parseInt(item)>1000){
            result='库存充足';
        }else if(parseInt(item)>10){
            result='库存：'+item+' 件';
        }else if(parseInt(item)>=1){
            result='仅剩：'+item+' 件';
        }else{
            result='库存：'+item+' 件';
        }
        return result;
    };
});
grApp.filter('isHasMore',function(){
    var result='';
    return function(item,account){
        if(account === 0){
            result='没有了...';
        }else if(parseInt(item)>=account ){
            result='没有了...';
        }else{
            result="查看更多";
        }
        return result;
    };
});
var each = 99;
var mini = 1 ;
var discount = 100;
var canAccount = 1 ;
var cart = 1;
var ueach = 0;
var canMinBuy = -1;
var normalProduct = 1 ;
var isLimitClassify = 0;
function startFirst(finalResult,limitClassify){
    if(finalResult.normalProduct === 0){
        discount = parseInt( finalResult.limitCondition.discount);
        each = parseInt(finalResult.limitCondition.each);
        mini = parseInt(finalResult.limitCondition.mini);
        if(finalResult.limitCondition.discount.ueach!=0){
            ueach = finalResult.limitCondition.ueach ;
            //还可以购买数量
            canMinBuy = parseInt(ueach) - parseInt(finalResult.limitPersonalBought) ;
        }
        if(finalResult.isInDate === 1){
            canAccount = parseInt(finalResult.canAccount);
            if(finalResult.isLoop === 1){
                if(finalResult.isInTime === 1){
                    canAccount = 1 ;
                    cart =parseInt( finalResult.limitCondition.cart);
                }else{
                    cart = 0;
                    canAccount = 0 ;
                }
            }else{
                cart =parseInt( finalResult.limitCondition.cart);
            }
        }else{
            cart = 0;
            canAccount = 0 ;
        }
    }else if(JSON.stringify(limitClassify)!='{}'){
        if(limitClassify.status === 1){
            isLimitClassify = 1 ;   //是否为按分类限制商品
            if(limitClassify.order_max != -1){
                each = parseInt(limitClassify.order_max);        // 该商品最大购买数量
            }
            mini = parseInt(limitClassify.order_mini);   //该商品最小起卖数量
            canAccount = parseInt(limitClassify.showAccount);
            cart = parseInt(limitClassify.showCart);
        }
    }
}
grApp.controller('DetailCtrl',['$scope','$http','toaster','NavbarFactory',function($scope,$http,toaster,navbarFactory){

    $scope.load = function(cartAllNumber,psid,price,inventory,salenum,finalResult,limitClassify){
        finalResult = JSON.parse(finalResult);
        limitClassify = JSON.parse(limitClassify);
        each = 99;
        mini = 1 ;
        discount = 100;
        canAccount = 1 ;
        cart = 1;
        canMinBuy = -1;
        startFirst(finalResult,limitClassify);
        $scope.price=parseFloat(price) * parseFloat(discount) * 0.01;
        $scope.inventory = isNaN(inventory)?0:inventory;
        $scope.canMinBuy = canMinBuy;
        //console.log((canMinBuy));
        $scope.canAccount = ((canMinBuy==-1 || canMinBuy>0) && canAccount==1 && $scope.inventory>0)?true:false;
        $scope.canCart = ((canMinBuy==-1 || canMinBuy>0) && cart==1 && $scope.inventory>0)?true:false;
        $scope.salenum = salenum;
        $scope.radio = {isChecked:psid};
        $scope.cartNumber = cartAllNumber;
        if($scope.inventory < 1){
            toaster.error('库存不足，采购小哥疯狂采购中~~');
            $scope.data={size:0};
        }else{
            $scope.data={size:1};
        }
        $scope.AllComment=[];
        $scope.page=1;
        $scope.limit=10;
        if(canMinBuy === 0){
            toaster.success('限购商品，请选择其他规格商品');
        }
     /*   if(isLimitClassify === 1){
            toaster.success('该商品必须至少购买'+limitClassify.cid_mini+'份，或者'+limitClassify.cid_mini+'种商品');
        }*/
    }

    //添加数量（默认为1）
    //各种按钮操作
    $scope.select = function(args,args1,args2,args3,args4){
        args3 = JSON.parse(args3);
        args4 = JSON.parse(args4)
        each = 99;
        mini = 1 ;
        discount = 100;
        canAccount = 1 ;
        cart = 1;
        canMinBuy = -1;
        //startFirst(args3);
        startFirst(args3,args4);
        //console.log(canMinBuy);
        $scope.price=parseInt(args) * parseInt(discount) * 0.01;
        $scope.data.size = mini ;
        $scope.inventory = isNaN(args1)?0:args1;
        $scope.canAccount = ((canMinBuy==-1 || canMinBuy>0) && canAccount==1 && $scope.inventory>0)?true:false;
        //console.log( canMinBuy+":"+$scope.canAccount);
        $scope.canCart = ((canMinBuy==-1 || canMinBuy>0) &&  cart==1 && $scope.inventory>0)?true:false;
        $scope.salenum = args2;
        if($scope.inventory < 1){
            toaster.error('库存不足，采购小哥疯狂采购中~~');
            $scope.data={size:0};
        }else{
            $scope.data={size:1};
        }
        if(canMinBuy === 0){
            toaster.success('限购商品，请选择其他规格商品');
        }

    };

    /**
     * 减少数量
     */
    $scope.minus = function(){
        if($scope.inventory < 1){
            $scope.data={size:0};
        }else{

            $scope.data.size = (parseInt($scope.data.size) > mini)?(parseInt($scope.data.size)-1):mini;
            if(isLimitClassify === 1 ){
                $scope.canAccount = ($scope.data.size>mini && $scope.inventory>0)?true:false;
            }
        }
    };
    /**
     *  增加购买数量
     */
    $scope.plus = function(){
        if($scope.inventory < 1){
            toaster.error('库存不足');
            $scope.data={size:0};
        }else{
            var inventory  = $scope.inventory;
            var size = $scope.data.size;
            var maxSize = (inventory >= each)?each:inventory;
            $scope.data.size = (parseInt(size) < maxSize)?(parseInt(size)+1):maxSize;
            if(isLimitClassify === 1 ){
                //$scope.canAccount = ($scope.data.size>=mini && $scope.inventory>0)?true:false;
                $scope.canAccount = false;
            }
        }
    };

    $scope.setCollect = function(objid){
        var pid = objid;
        //判断是否收藏
        navbarFactory.setCollect(pid).then(function(res){
            if(res.flag === 1){
                $scope.iscollect=1;
                toaster.success('添加收藏成功');
            }else{
                $scope.iscollect=0;
                toaster.success('取消收藏成功');
            }
        }).catch(function(err){
            toaster.error('出错了');
        });
    };

    $scope.addToCart = function(objid){
        var pid = objid;

        //获取选中的规格id
        var psid = $scope.radio.isChecked;
        var num = $scope.data.size;
        //if($scope.inventory == 0){
        //    toaster.error('库存不足，采购小哥疯狂采购中……');
        //    return;
        //}
        //console.log('pid:'+num);
        navbarFactory.addToCart(pid,psid,num).then(function(res){

            $scope.cart = 1;
            toaster.success('成功添加'+num+'件购物车');
            $scope.cartNumber = parseInt(isNaN($scope.cartNumber)?0:$scope.cartNumber) + parseInt(num);

            //if(res.code==-1){
            //    toaster.error('库存不足，采购小哥疯狂采购中……');
            //    return;
            //}
            //if(res.code === 0){
            //    //alert('添加购物车成功');
            //    $scope.cart = 1;
            //    toaster.success('成功添加'+res.number+'件购物车');
            //    $scope.cartNumber = parseInt(isNaN($scope.cartNumber)?0:$scope.cartNumber) + parseInt(num);
            //    $scope.inventory = res.inventory;
            //    //console.log('添加购物车成功');
            //}else{
            //    $scope.cart = 2;
            //    toaster.error('添加购物车失败2');
            //}
        }).catch(function(err){
            toaster.error('添加购物车失败');
        });
    };
    $scope.account = function(objid){
        var progress = $.AMUI.progress;
        var $modal = angular.element("#my-modal-loading");
        progress.start();
        $modal.modal();
        //console.log('cart：'+cart)
        var pid = objid;
        var psid = $scope.radio.isChecked;
        var num = $scope.data.size;
        //if($scope.inventory <= 0){
        //    toaster.success('库存不足，采购小哥疯狂采购中……');
        //    $modal.modal('close');
        //    return;
        //}
        navbarFactory.accountNow(pid,psid,num,cart).then(function(res){
            //console.log(res);
            if(res.code === 0){
                //console.log('立即购买购物车设置成功');
                //跳转到购物车

                //orderid = req.uid();
                //window.location.href='/cart/singlebuy?cartproductid='+res.cartProductID;

                navbarFactory.singlebuy(res.cartProductID).then(function (data) {
                    if(data.code == 509){
                        alert('商品库存不足:'+data.msg);
                    }else if(data.code == 510){
                        alert('购物车内无商品');
                    }else{
                        //成功
                        window.location.href="/order/confirmOrder/0_"+data;
                    }
                });
            }
        }).catch(function(err){
            console.log(err);
        });
    };
    $scope.getComment = function(pid){
        var page = $scope.page;
        var limit =$scope.limit;
        navbarFactory.getAllComment(pid,page,limit).then(function(res){
            var comment=res.list;
            for(var index in comment){
                $scope.AllComment.push(comment[index]);
                $scope.commentCount = $scope.AllComment.length;
                //console.log(comment[index]);
            }
            $scope.page++;
        }).catch(function(err){
            console.log(err);
        });
    }
}]);


grApp.factory('NavbarFactory',['$http','$q',function($http,$q){
    var service = {};
    //取消、添加收藏
    service.setCollect = function(pid){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/product/selected',
            params:{pid:pid}
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };
    service.addToCart= function (pid,psid,num) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/product/addToCart',
            params:{pid:pid,psid:psid,num:num}
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    service.accountNow = function(pid,psid,num,cart){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/product/accountNow',
            params:{pid:pid,psid:psid,num:num,cart:cart}
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    service.singlebuy = function(cartproductid){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/singlebuy',
            params:{cartproductid:cartproductid}
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    service.getCartNumber = function(){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/product/getCartNumber'
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };
    service.getAllComment = function(pid,page,limit){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/product/getAllComment',
            params:{pid:pid,page:page,limit:limit}
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    }
    return service;
}]);
